package com.lihan.GetSeatInLib.Service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.lihan.GetSeatInLib.Domain.Order;
import com.lihan.GetSeatInLib.Domain.User;
import com.lihan.GetSeatInLib.Domain.Enums.OrderStatus;
import com.lihan.GetSeatInLib.Domain.MailModel.MailTemplate;
import com.lihan.GetSeatInLib.Repository.OrderRepository;
import com.lihan.GetSeatInLib.Service.MailService;
import com.lihan.GetSeatInLib.Service.OrderService;
import com.lihan.GetSeatInLib.Tools.CommonFinal;

@Service
public class OrderServiceImpl implements OrderService{

	@Autowired
	private OrderRepository _orderdao;
	
	@Autowired
	private MailService _mailservice;
	
	@Override
	public boolean CreateOrder(Order order) {
		try {
			
			_orderdao.save(order);
			
			
			MailTemplate template = new MailTemplate();
			template.setTitle("预定成功通知");
			template.setTo(order.getOwner().getEmail());
			template.setFrom(CommonFinal.SENDER_MAIL);
			template.setSendDate(new Date());
			template.setVerifyCode(null);   //此为通知邮件没有验证码
			HashMap<String, String> map = new HashMap<String, String>();
			//将一下两个参数传到模板里
			map.put("UserName", order.getOwner().getUserName());
			map.put("SeatID", String.valueOf(order.getSeat().getID()));
			
			template.setContext(map);
			
			if(_mailservice.SendMail(template, "Announce.html"))			
				return true;			
			return false;			
		}catch (Exception e) {
			return false;
		}
	}

	@Override
	public boolean CancelOrder(Order order) {
		
		try {
			order.setStatus(OrderStatus.Canceled);
			return true;
		}catch (Exception e) {
			return false;
			// TODO: handle exception
		}
	}

	@Override
	public boolean UpdateOrder(Order order) {
		return _orderdao.save(order) != null;
	}

	@Override
	public Order QueryOrderById(Long ID) {
		return _orderdao.getById(ID);
	}

	@Cacheable(cacheNames = "TheOrderOf",key = "#user.UserName")
	@Override
	public List<Order> QueryOrderByUser(User user) {
		return _orderdao.QueryOrderByUser(user);
	}
	
	@Override
	public void StopOrderInAdvance(Order order) {
		order.setQuitTime(new Date());
		_orderdao.save(order);	
	}

	@Override
	public List<Order> QueryUsedOrders() {
		return _orderdao.QueryUsedOrders();
	}
}
